package com.lcc.forum.demos.web.controller;

import com.lcc.forum.demos.web.common.AppResult;
import com.lcc.forum.demos.web.common.ResultCode;
import com.lcc.forum.demos.web.config.AppConfig;
import com.lcc.forum.demos.web.model.Message;
import com.lcc.forum.demos.web.model.User;
import com.lcc.forum.demos.web.services.IMessageService;
import com.lcc.forum.demos.web.services.IUserService;
import com.lcc.forum.demos.web.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/message")
@Slf4j
@Api(tags = "站内信接⼝")
public class MessageController {
    @Resource
    private IMessageService messageService;
    @Resource
    private IUserService userService;
    @ApiOperation("发送站内信")
    @PostMapping("/send")
    public AppResult send(HttpServletRequest request,
                          @ApiParam("接收者Id") @RequestParam("receiveUserId") @NonNull Long receiveUserId,
                          @ApiParam("内容") @RequestParam("content") @NonNull String content){
        //当前登录用户如果被禁言则不能发送站内信
        //获取当前登录的用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1){
            return AppResult.failed("不能给自己发送站内信");
        }
        //不能给自己发送站内信
        if (receiveUserId == user.getId()){
            return AppResult.failed(ResultCode.FAILED_CREATE);
        }
        //校验接收者是否存在
        User receiveUser = userService.selectById(receiveUserId);
        if (receiveUser == null || receiveUser.getDeleteState() == 1){
//            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);//不要提示的太明显，避免出现恶意攻击者来破解
            return AppResult.failed("接收者状态异常");
        }
        //封装对象
        Message message = new Message();
        message.setPostUserId(user.getId());//发送用户
        message.setReceiveUserId(receiveUserId); //接收用户
        message.setContent(content);//发送内容
        //调用service
        messageService.create(message);
        //返回结果
        return AppResult.success("发送成功");
    }
    @ApiOperation("获取未读数量")
    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount(HttpServletRequest request){
        //获取当前登录用户的Id
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //调用service
        Integer count = messageService.selectUnreadCount(user.getId());
        //返回结果
        return AppResult.success(count);
    }
    @ApiOperation("查询用户所有站内信")
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAll(HttpServletRequest request){
        //获取当前登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //调用service
        List<Message> messages = messageService.selectByReceiveUserId(user.getId());
        //返回结果
        return AppResult.success(messages);
    }
    @ApiOperation("根据用户Id更新站内信的状态为已读")
    @PostMapping("/markRead")
    public AppResult markRead(HttpServletRequest request,@ApiParam("站内信Id") @RequestParam("id") @NonNull Long id){
        //根据Id查询站内信校验站内信是否存在
        Message message = messageService.selectById(id);
        if(message == null || message.getDeleteState() == 1){
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        //判断站内信是否是自己的
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (message.getReceiveUserId() != user.getId()){
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //调用Service更新站内信的状态为已读
        messageService.updateStateById(id, (byte) 1);
        //返回结果
        return AppResult.success();
    }
    @ApiOperation("回复站内信")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,
                           @ApiParam("要回复的站内信Id") @RequestParam("repliedId") @NonNull Long repliedId,
                           @ApiParam("要回复的内容") @RequestParam("content") @NonNull String content){
        //校验当前用户是否是禁言状态，如果禁言，则不能回复
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user == null || user.getDeleteState() == 1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //校验要回复的站内信的状态
        Message message = messageService.selectById(repliedId);
        if (message == null || message.getDeleteState() == 1){
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        //校验需要回复的站内信的接收者Id是否和当前登录的用户Id一样，不一样则不能回复
        if (user.getId() != message.getReceiveUserId()){
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        //需要回复的站内信的发送者不能是当前登录者，因为自己不能给自己回复
        if (user.getId() == message.getPostUserId()){
            //返回错误信息
            return AppResult.failed("不能回复自己的站内信");
        }
        //校验参数：content为空则不能回复成功
        if (StringUtil.isEmpty(content)){
            return AppResult.failed("请输入要回复的内容");
        }
        //构造要回复的Message对象
        Message updateMessage = new Message();
        updateMessage.setReceiveUserId(message.getPostUserId());
        updateMessage.setPostUserId(user.getId());
        updateMessage.setContent(content);
        //调用service
        messageService.reply(repliedId,updateMessage);
        //返回结果
        return AppResult.success();
    }
}
